package us.gaaoc.framework.webapp.controllers;

import java.io.IOException;
import java.io.OutputStream;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import us.gaaoc.framework.model.Documents;
import us.gaaoc.framework.webapp.util.BufferedImageCreatorPDFRendererImpl;
import us.gaaoc.framework.webapp.util.PDFToImage;

/**
 * Controller which exposes the PDF documents as
 * JPG images, for in-browser rendering.
 * 
 * @author artripa
 *
 */
@Controller
public class PdfImageController {
	
	Logger log = Logger.getLogger(PdfImageController.class);
	
	@Autowired SessionFactory sessionFactory;

	@RequestMapping(value="/pdftoimage",method=RequestMethod.GET)	
	public void streamImageContent(
				@RequestParam("id") String documentId,
				@RequestParam("page") int pageNumber, 
				@RequestParam("empty") int empty,
				HttpServletRequest req,
				HttpServletResponse res, 
				OutputStream outputStream)
		throws IOException {

		// If we add empty, we just want to get validation that the document exists (200 OK) and do not want the
		// document body. This is a hack to work around jquery galleria prefetching documents.
		if (empty == 1) {
			res.sendRedirect(
				req.getContextPath() +
					"/secure/sign/stock_new-text.png");
			return;
		}
		
		
		Documents document = (Documents) sessionFactory.getCurrentSession().get(Documents.class,documentId);

		
		//byte[] contents = d.getContent();
		outputStream.write(PDFToImage.toImage(
				new BufferedImageCreatorPDFRendererImpl(pageNumber),
				document,
				pageNumber));

		res.setHeader("no-store", "true");
		res.setHeader("no-cache", "true");
		
	}

}
